#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WMS Sample 系统一键打包脚本
打包三个应用程序：主程序、客户端、服务管理工具
"""

import os
import sys
import subprocess
import shutil
from datetime import datetime

def run_command(cmd, description):
    """运行命令并显示进度"""
    print(f"\n{'='*50}")
    print(f"正在{description}...")
    print(f"命令: {cmd}")
    print(f"{'='*50}")
    
    try:
        result = subprocess.run(cmd, shell=True, check=True, 
                              capture_output=True, text=True, encoding='utf-8')
        print(f"✅ {description}成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description}失败")
        print(f"错误信息: {e.stderr}")
        return False

def clean_build_dirs():
    """清理构建目录"""
    dirs_to_clean = ['build', 'dist']
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            print(f"清理目录: {dir_name}")
            shutil.rmtree(dir_name)

def create_release_package():
    """创建发布包"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    release_dir = f"release_{timestamp}"
    
    if os.path.exists(release_dir):
        shutil.rmtree(release_dir)
    
    os.makedirs(release_dir)
    
    # 复制可执行文件
    exe_files = [
        ('dist/wms_simple/wms_simple.exe', 'wms_sample.exe'),
        ('dist/wms_sample_client.exe', 'wms_sample_client.exe'),
        ('dist/service_config_manager.exe', 'service_config_manager.exe'),
        ('dist/wms_service/wms_service.exe', 'wms_service.exe')
    ]
    
    for src, dst in exe_files:
        if os.path.exists(src):
            shutil.copy2(src, os.path.join(release_dir, dst))
            print(f"复制: {src} -> {dst}")
    
    # 复制配置文件和文档
    config_files = [
        'config.json',
        'client_config.json',
        'requirements.txt',
        'LICENSE'
    ]
    
    for file in config_files:
        if os.path.exists(file):
            shutil.copy2(file, release_dir)
    
    # 复制批处理文件
    bat_files = [
        '启动WMS系统.bat',
        '启动客户端.bat', 
        '服务管理工具.bat'
    ]
    
    for file in bat_files:
        if os.path.exists(file):
            shutil.copy2(file, release_dir)
    
    # 复制文档目录
    if os.path.exists('docs'):
        shutil.copytree('docs', os.path.join(release_dir, 'docs'))
    
    print(f"\n✅ 发布包创建完成: {release_dir}")
    return release_dir

def main():
    """主函数"""
    print("WMS Sample 系统一键打包工具")
    print("="*50)
    
    # 检查PyInstaller（使用虚拟环境）
    python_exe = r'D:\python\wms_env\Scripts\python.exe'
    pyinstaller_exe = r'D:\python\wms_env\Scripts\pyinstaller.exe'
    
    try:
        subprocess.run([pyinstaller_exe, '--version'], check=True, 
                      capture_output=True)
        print(f"✅ 使用PyInstaller: {pyinstaller_exe}")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("❌ 未找到PyInstaller，请先安装: pip install pyinstaller")
        return False
    
    # 清理旧的构建文件
    clean_build_dirs()
    
    # 打包应用程序
    apps = [
        ('wms_simple.spec', '主程序(WMS Sample)'),
        ('client_gui.spec', '客户端程序'),
        ('service_config_manager.spec', '服务管理工具'),
        ('wms_service.spec', 'Windows服务程序')
    ]
    
    success_count = 0
    for spec_file, description in apps:
        if os.path.exists(spec_file):
            cmd = f'"{pyinstaller_exe}" --clean {spec_file}'
            if run_command(cmd, f"打包{description}"):
                success_count += 1
        else:
            print(f"⚠️  配置文件不存在: {spec_file}")
    
    print(f"\n{'='*50}")
    print(f"打包完成统计: {success_count}/{len(apps)} 个应用程序打包成功")
    
    if success_count > 0:
        # 创建发布包
        release_dir = create_release_package()
        
        print(f"\n📦 发布包位置: {os.path.abspath(release_dir)}")
        print("\n🎉 打包完成！可执行文件位于以下位置:")
        
        for root, dirs, files in os.walk('dist'):
            for file in files:
                if file.endswith('.exe'):
                    print(f"  - {os.path.join(root, file)}")
    
    return success_count == len(apps)

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1) 